package org.robot.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

public class MatchEmail {

	/**
	 * 返回匹配的作者
	 * @param authors
	 * @param email
	 * @return
	 */
	public static String similarName(String[] authors, String email) {
		if (authors.length == 0) {
			return "";
		}
		else if (authors.length == 1) {
			return authors[0];
		}
		String result = "";
		if (email.contains("@")) {
			String preEmail = email.toLowerCase().substring(0, email.indexOf("@"));
			double max = 0;
			for (String author : authors) {
				String preAuthor = author.replace(" ", "").toLowerCase();
				int lcsLength = lcs(preAuthor, preEmail);
				double similarity = (double) lcsLength / (preAuthor.length() + preEmail.length() - lcsLength);
				if (max < similarity) {
					max = similarity;
					result = author;
				}
			}
		}
		if (result.isEmpty()) {
			return authors[0];
		}
		return result;
	}

	/**
	 *  tpaul  5
	 *  pult   4
	 * @return
	 */
	private static int lcs(String param1, String param2) {
		int substringLength1 = param1.length();
		int substringLength2 = param2.length();
		int[][] opt = new int[substringLength1 + 1][substringLength2 + 1];
		for (int i = substringLength1 - 1; i >= 0; i--) {
			for (int j = substringLength2 - 1; j >= 0; j--) {
				if (param1.charAt(i) == param2.charAt(j)) {
					opt[i][j] = opt[i + 1][j + 1] + 1;
				} else {
					opt[i][j] = Math.max(opt[i + 1][j], opt[i][j + 1]);
				}
			}
		}
		return opt[0][0];
	}
	
	public static void main(String[] args) {
		String str = getContent(new File("E:/aa.pdf"));
//		List<String> email = getEmailByString(str);
		System.out.println(str);
	}
	

	/**
	 * 取得字符串中的邮箱
	 * @param str
	 * @return
	 */
	public static List<String> getEmailByString(String str){
		try {
			List<String> lst = new ArrayList<String>();
			//^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$
			//\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*
			String mailreg="\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
			Pattern p=Pattern.compile(mailreg, Pattern.CASE_INSENSITIVE); 
			Matcher m=p.matcher(str);
			while(m.find()) {
				String email=m.group();
				lst.add(email);
			}
			if(lst.size()<=0){//如果取不到email 则去掉所有的空格在取一次
				str = str.replaceAll(" ", "");
				Pattern p1=Pattern.compile(mailreg);
				Matcher m1=p1.matcher(str);
				while(m1.find()) {
					String email=m1.group();
					lst.add(email);
				}
			}
			return lst;
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 全部转成小写
	 * 取得字符串中的邮箱并添加到一个set中，不添加重复邮箱
	 * @param str
	 * @return
	 */
	public static Set<String> getEmailByStr(String str){
		try {
			Set<String> lst = new HashSet<String>();
			String mailreg="\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";//"[+\\w+[_.]]+@+[\\w[.-]]+\\.\\w+";
			Pattern p=Pattern.compile(mailreg);
			Matcher m=p.matcher(str);
			while(m.find()) {
				String email=m.group();
				lst.add(email.toLowerCase());
			}
			if(lst.size()<=0){//如果取不到email 则去掉所有的空格在取一次
				str = str.replaceAll(" ", "");
				Pattern p1=Pattern.compile(mailreg);
				Matcher m1=p1.matcher(str);
				while(m1.find()) {
					String email=m1.group();
					lst.add(email.toLowerCase());
				}
			}
			return lst;
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String getContent(File file) {
		StringBuffer content = new StringBuffer("");
		PDDocument pdfDocument = null; 
		try { 
			FileInputStream fis = new FileInputStream(file); 
			PDFTextStripper stripper = new PDFTextStripper(); 
			pdfDocument = PDDocument.load(fis); 
			StringWriter writer = new StringWriter(); 
//			System.out.println("fis:"+fis+"----"+pdfDocument);
			stripper.writeText(pdfDocument, writer); 
			content.append(writer.getBuffer().toString()); 
			fis.close(); 
		} catch (Exception e) { 
			throw new RuntimeException(e);
//				content.append(file.getName());
		} finally { 
			if (pdfDocument != null) { 
				try {
					COSDocument cos = pdfDocument.getDocument(); 
					cos.close();
					pdfDocument.close(); 
				} catch (IOException e) {
					try {
						pdfDocument.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					} 
				} 
				
			} 
		} 
		return content.toString();
	}
	
	/**
	 * 从pdf中读取email，不存在返回null
	 * @param pdfFile
	 * @return
	 */
	public static String getEmailString(File pdfFile) {
		String str = null;
		try {
			str = getContent(pdfFile);
		} catch (Exception e) {
			e.printStackTrace();
//			pdfFile.delete();
			return null;
		}
		Set<String> emailList = getEmailByStr(str);
		String emails = null;
		if (emailList != null && !emailList.isEmpty()) {
			emails = "";
			for (String email : emailList) {
				emails += "^" + email;
			}
			emails = emails.replaceFirst("\\^", "");
		}
		return emails;		
	}

	public static String getFirstEmail(String str) {
		String email = null;
		String mailreg="\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		Pattern p=Pattern.compile(mailreg, Pattern.CASE_INSENSITIVE); 
		Matcher m=p.matcher(str);
		if (m.find()) 
			email=m.group();
		else {//去掉空白字符再取一次
			str = str.replaceAll("\\s", "");
			Pattern p1=Pattern.compile(mailreg, Pattern.CASE_INSENSITIVE); 
			Matcher m1=p1.matcher(str);
			if (m1.find())
				email = m1.group();
		}
		return email;
	}
	
	
}
